﻿using DailyApp.WPF.DTOs;
using DailyApp.WPF.HttpClients;
using DailyApp.WPF.Models;
using DailyApp.WPF.Service;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace DailyApp.WPF.ViewModels
{
    internal class HomeUCViewModel : BindableBase, INavigationAware
    {
        #region 统计面板数据
        private List<StartPanelInfo> _statPanelList;        
        /// <summary>
        /// 统计面板数据
        /// </summary>
        public List<StartPanelInfo> StatPanelList
        {
            get { return _statPanelList; } 
            set
            {
                _statPanelList = value;
                RaisePropertyChanged();
            }
        }

        #endregion


        #region 待办事项数据
        private List<WaitInfoDTO> _WaitList;
        /// <summary>
        /// 待办事项数据
        /// </summary>
        public List<WaitInfoDTO> WaitList
        {
            get { return _WaitList; }
            set
            {
                _WaitList = value;
                RaisePropertyChanged();
            }
        }
        #endregion

        #region 备忘录数据
        private List<MemoInfoDTO> _MemoList;
        /// <summary>
        /// 备忘录数据
        /// </summary>
        public List<MemoInfoDTO> MemoList
        {
            get { return _MemoList; }
            set
            {
                _MemoList = value;
                RaisePropertyChanged();
            }
        }

        #endregion

        private readonly HttpRestClient httpRestClient;//请求api的客户端
        //private readonly IDialogService DialogService;//自带对话服务
        private readonly DialogHostService dialogHostService;//自定义对话服务

        /// <summary>
        /// 构造函数
        /// </summary>
        public HomeUCViewModel(HttpRestClient _httpRestClient, DialogHostService _dialogHostService, IRegionManager _regionManager)
        {

            httpRestClient = _httpRestClient;
            regionManager = _regionManager;
            NavigateCmm = new DelegateCommand<StartPanelInfo>(Navigate);
            ShowAddWaitDialogCmm = new DelegateCommand(ShowAddWaitDialog);
            ShowEditWaitDialogCmm = new DelegateCommand<WaitInfoDTO>(ShowEditWaitDialog);

            ShowAddMemoDialogCmm = new DelegateCommand(ShowAddMemoDialog);
            ShowEditMemoDialogCmm = new DelegateCommand<MemoInfoDTO>(ShowEditMemoDialog);
            //DialogService = _dialogService;
            dialogHostService = _dialogHostService;
            CreateStartPanel();
            GetWaitingList();
            GetMemoList();
            ChangeWaitStatusCmm = new DelegateCommand<WaitInfoDTO>(ChangeWaitStatus);
        }
        /// <summary>
        /// 创建统计面板
        /// </summary>
        private void CreateStartPanel()
        {
            StatPanelList = new List<StartPanelInfo>();
            StatPanelList.Add(new StartPanelInfo() { Icon = "ClockFast", ItemName = "汇总", BackColor = "#FF0CA0FF", ViewName = "WaitUC", Result = "9" });
            StatPanelList.Add(new StartPanelInfo() { Icon = "ClockCheckOutline", ItemName = "已完成", BackColor = "#FF1ECA3A", ViewName = "WaitUC", Result = "9" });
            StatPanelList.Add(new StartPanelInfo() { Icon = "ChartLineVariant", ItemName = "完成比例", BackColor = "#FF02C6DC", Result = "90%" });
            StatPanelList.Add(new StartPanelInfo() { Icon = "PlaylistStar", ItemName = "备忘录", BackColor = "#FFFFA000", ViewName = "MemoUC", Result = "20" });
        }

        #region 统计面板导航
        public DelegateCommand<StartPanelInfo> NavigateCmm { get; set; }

        private readonly IRegionManager regionManager;
        private void Navigate(StartPanelInfo startPanelInfo)
        {
            if (!string.IsNullOrEmpty(startPanelInfo.ViewName))
            {
                if (startPanelInfo.ItemName == "已完成")
                {
                    NavigationParameters keyValuePairs = new NavigationParameters();
                    keyValuePairs.Add("SelectedIndex", 2);
                    regionManager.Regions["MainViewRegion"].RequestNavigate(startPanelInfo.ViewName,keyValuePairs);
                }
                else{
                    regionManager.Regions["MainViewRegion"].RequestNavigate(startPanelInfo.ViewName);
                }
                
            }
        }
        #endregion

        

        #region 显示登录登录用户信息

        private string _LoginInfo;

        public string LoginInfo
        {
            get { return _LoginInfo; }
            set { _LoginInfo = value; }
        }


        /// <summary>
        /// 接收导航处理
        /// </summary>
        /// <param name="navigationContext"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            if (navigationContext.Parameters.ContainsKey("LoginName"))
            {
                DateTime now = DateTime.Now;
                string[] week = new string[] { "星期日", "星期六", "星期五", "星期四", "星期三", "星期二", "星期一" };
                string loginName = navigationContext.Parameters.GetValue<string>("LoginName");
                LoginInfo = $"您好！{loginName}。今天是{now.ToString("yyyy-MM-dd")} {week[(int)now.DayOfWeek]}";
                CallStatWait();
                CallStatMemo();
            }
        }
        #endregion


        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            //throw new NotImplementedException();
        }

        /// <summary>
        /// 创建待办事项数据
        /// </summary>
        private void GetWaitingList()
        {
            WaitList = new List<WaitInfoDTO>();
            ApiRequest apiRequest = new ApiRequest();
            apiRequest.Method = RestSharp.Method.GET;
            apiRequest.Route = "Wait/GetWaiting";
            ApiResponse apiResponse = httpRestClient.Execute(apiRequest);
            if (apiResponse.ResultCode == 1)
            {
                WaitList = JsonConvert.DeserializeObject<List<WaitInfoDTO>>(apiResponse.ResultData.ToString());
                RefreshWaitStat();
            }
            else
            {
                WaitList = new List<WaitInfoDTO>();
                MessageBox.Show(apiResponse.Msg);
            }
        }

        #region 待办事项统计
        private StatWaitDTO statWaitDTO { get; set; } = new StatWaitDTO();

        /// <summary>
        /// 调用api获取数据
        /// </summary>
        private void CallStatWait()
        {
            ApiRequest apiRequest = new ApiRequest();
            apiRequest.Method = RestSharp.Method.GET;
            apiRequest.Route = "Wait/StatWait";
            ApiResponse apiResponse = httpRestClient.Execute(apiRequest);
            if (apiResponse.ResultCode == 1)
            {
                statWaitDTO = JsonConvert.DeserializeObject<StatWaitDTO>(apiResponse.ResultData.ToString());
                RefreshWaitStat();
            }
        }

        private void RefreshWaitStat()
        {
            StatPanelList[0].Result = statWaitDTO.TotalCount.ToString();
            StatPanelList[1].Result = statWaitDTO.FinishCount.ToString();
            StatPanelList[2].Result = statWaitDTO.FinishPercent;
        }
        #endregion

        #region 添加待办事项处理
        public DelegateCommand ShowAddWaitDialogCmm { get; set; }
        private async void ShowAddWaitDialog()
        {
            //DialogService.ShowDialog("AddWaitUC", callback =>
            //{

            //});
            var result = await dialogHostService.ShowDialog("AddWaitUC", null);
            if (result.Result == ButtonResult.OK)
            {
                //接收数据
                if (result.Parameters.ContainsKey("AddWaitInfo"))
                {
                    var addModel = result.Parameters.GetValue<WaitInfoDTO>("AddWaitInfo");
                    //调用api实现数据插入

                    ApiRequest apiRequest = new ApiRequest();
                    apiRequest.Method = RestSharp.Method.POST;
                    apiRequest.Parameters = addModel;
                    apiRequest.Route = "Wait/AddWait";
                    ApiResponse response = httpRestClient.Execute(apiRequest);
                    if (response.ResultCode == 1)
                    {
                        MessageBox.Show(response.Msg);
                        //刷新统计数据
                        CallStatWait();
                        GetWaitingList();
                    }
                    else
                    {
                        MessageBox.Show(response.Msg);
                    }
                }

            }
        }
        #endregion

        #region 修改待办事项的状态
        public DelegateCommand<WaitInfoDTO> ChangeWaitStatusCmm { get; set; }

        /// <summary>
        /// 修改待办事项的状态
        /// </summary>
        private void ChangeWaitStatus(WaitInfoDTO waitInfoDTO)
        {

            ApiRequest apiRequest = new ApiRequest();
            apiRequest.Method = RestSharp.Method.PUT;
            apiRequest.Parameters = waitInfoDTO;
            apiRequest.Route = "Wait/UpdateStatus";
            ApiResponse response = httpRestClient.Execute(apiRequest);
            if (response.ResultCode == 1)//修改成功
            {
                GetWaitingList();//刷新列表
                CallStatWait();//刷统计数据
            }
            else
            {
                MessageBox.Show(response.Msg);
            }
        }
        #endregion

        #region 编辑待办事项的内容
        public DelegateCommand<WaitInfoDTO> ShowEditWaitDialogCmm { get; set; }

        /// <summary>
        /// 编辑待办事项的内容
        /// </summary>
        private async void ShowEditWaitDialog(WaitInfoDTO waitInfoDTO)
        {
            DialogParameters dialogParameters = new DialogParameters();
            dialogParameters.Add("OldWaitInfo", waitInfoDTO);
            var result = await dialogHostService.ShowDialog("EditWaitUC", dialogParameters);
            if (result.Result == ButtonResult.OK)
            {
                //接收数据
                if (result.Parameters.ContainsKey("NewWaitInfo"))
                {
                    var addModel = result.Parameters.GetValue<WaitInfoDTO>("NewWaitInfo");
                    //调用api实现数据编辑

                    ApiRequest apiRequest = new ApiRequest();
                    apiRequest.Method = RestSharp.Method.PUT;
                    apiRequest.Parameters = addModel;
                    apiRequest.Route = "Wait/EditWait";
                    ApiResponse response = httpRestClient.Execute(apiRequest);
                    if (response.ResultCode == 1)
                    {
                        MessageBox.Show(response.Msg);
                        //刷新统计数据
                        CallStatWait();
                        GetWaitingList();
                    }
                    else
                    {
                        MessageBox.Show(response.Msg);
                    }
                }

            }
        }
        #endregion

        #region 备忘录
        /// <summary>
        /// 备忘录数据统计
        /// </summary>
        private void CallStatMemo()
        {
            ApiRequest apiRequest = new ApiRequest();
            apiRequest.Method = RestSharp.Method.GET;
            apiRequest.Route = "Memo/StatMemo";

            ApiResponse response = httpRestClient.Execute(apiRequest);

            if (response.ResultCode == 1)
            {
                StatPanelList[3].Result = response.ResultData.ToString();
            }
        }

        //显示添加备忘录视图命令
        public DelegateCommand ShowAddMemoDialogCmm { get; set; }

        /// <summary>
        /// 显示添加备忘录视图
        /// </summary>
        private async void ShowAddMemoDialog()
        {
            var result = await dialogHostService.ShowDialog("AddMemoUC", null);//await等待

            if (result.Result == ButtonResult.OK)
            {
                //接收数据
                if (result.Parameters.ContainsKey("AddMemoInfo"))
                {
                    var addModel = result.Parameters.GetValue<MemoInfoDTO>("AddMemoInfo");

                    //调用api实现添加备忘录

                    ApiRequest apiRequest = new ApiRequest();
                    apiRequest.Method = RestSharp.Method.POST;
                    apiRequest.Parameters = addModel;
                    apiRequest.Route = "Memo/AddMemo";
                    ApiResponse response = httpRestClient.Execute(apiRequest);
                    if (response.ResultCode == 1)//添加成功
                    {
                        MessageBox.Show(response.Msg);
                        //刷新备忘录统计数据
                        CallStatMemo();

                        //刷新列表
                       GetMemoList();
                    }
                    else
                    {
                        MessageBox.Show(response.Msg);
                    }
                }
            }
        }

        /// <summary>
        /// 获取备忘录数据
        /// </summary>
        private void GetMemoList()
        {
            ApiRequest apiRequest = new ApiRequest();
            apiRequest.Method = RestSharp.Method.GET;
            apiRequest.Route = "Memo/QueryMemo";

            ApiResponse response = httpRestClient.Execute(apiRequest);

            if (response.ResultCode == 1)//获取成功
            {
                MemoList = JsonConvert.DeserializeObject<List<MemoInfoDTO>>(response.ResultData.ToString());
            }
            else
            {
                MemoList = new List<MemoInfoDTO>();
            }
        }

        /// <summary>
        /// 显示备忘录编辑界面
        /// </summary>
        public DelegateCommand<MemoInfoDTO> ShowEditMemoDialogCmm { get; set; }

        private async void ShowEditMemoDialog(MemoInfoDTO memoInfoDTO)
        {
            DialogParameters paras = new DialogParameters();
            paras.Add("OldMemoInfo", memoInfoDTO);

            var result = await dialogHostService.ShowDialog("EditMemoUC", paras);//await等待

            if (result.Result == ButtonResult.OK)
            {
                //接收数据
                if (result.Parameters.ContainsKey("NewMemoInfo"))
                {
                    var newModel = result.Parameters.GetValue<MemoInfoDTO>("NewMemoInfo");

                    //调用api实现编辑备忘录

                    ApiRequest apiRequest = new ApiRequest();
                    apiRequest.Method = RestSharp.Method.PUT;
                    apiRequest.Parameters = newModel;
                    apiRequest.Route = "Memo/EditMemo";
                    ApiResponse response = httpRestClient.Execute(apiRequest);
                    if (response.ResultCode == 1)//编辑成功
                    {
                        MessageBox.Show(response.Msg);

                        GetMemoList();//刷新列表
                    }
                    else
                    {
                        MessageBox.Show(response.Msg);
                    }
                }
            }
        }
        #endregion
    }
}
